<template>
	<PageLayout title="飞行调度">
		<view v-if="UpdateInterfaceData.interfaceVisual!='hide'"
			style="display: flex;flex-direction: column;position: fixed;width: calc(100vw - 20px);height: calc(100vh - 150px);background-color: #ffffff;z-index: 2;border-radius: 20px;border: 2px solid #cfcfcf;margin: 7px;">
			<view style="height: 30%;width: 100% ;display: flex;align-items: center;align-items: center;">
				<view
					style="width: calc(100% - 20px);;height: 100px;border-radius: 20px;background-color: #ffffff;margin-bottom: 20px;display: flex;flex-direction: row;align-items: center;"
					:style="{color: UpdateInterfaceData.enabled ? '#1296db' : '#bababa' }">
					<view style="width: 100%;margin-left: 20px;display: flex;flex-direction: column;">
						<view style="display: flex;flex-direction: row;align-items: center;">
							<text style="font-size: 28px;margin-right: 4px;">
								{{ formatTime(UpdateInterfaceData.startTime) }}
							</text>
							<text style="font-size: 20px;margin-top: 4px;">
								{{ UpdateInterfaceData.routeId }}号路线
							</text>
						</view>
						<view style="display: flex;flex-direction: row;align-items: center;">
							<text style="font-size: 14px;margin-right: 4px;">
								{{ UpdateInterfaceData.droneId }}号无人机
							</text>
							<text style="font-size: 14px;">
								{{ formatDate(UpdateInterfaceData.scheduleType,UpdateInterfaceData.whichDay) }}
							</text>
						</view>
					</view>
					<image
						:src="UpdateInterfaceData.enabled ? '/static/icons/switch_on.png' : '/static/icons/switch_off.png'"
						mode="aspectFit" style="height: 80px;width: 80px;margin-right: 20px;z-index: 3;"
						@click="switchUpdateInterfaceDataEnabled()" />
				</view>
			</view>
			<view
				style="height: 70%;width: 100% ;display: flex;align-items: start;align-items: center;flex-direction: column;font-size: 20px;color:#484848 ;">
				<view
					style="width: calc(100% - 40px);display: flex;align-items: center;margin-bottom: 10px;border-bottom: #cecece 2px solid;padding: 10px;">
					<picker mode="selector" :range="droneIdList" @change="handlecurrentSelectDroneIdChange"
						style="display: flex;justify-content: center;align-items: center;">
						<view v-if="hasChooseDrone">{{ '无人机id：' + UpdateInterfaceData.droneId}}</view>
						<view v-if="!hasChooseDrone">{{'请选择无人机' }}</view>
					</picker>
				</view>
				<view
					style="width: calc(100% - 40px);display: flex;align-items: center;margin-bottom: 10px;border-bottom:#cecece 2px solid;padding: 10px;">
					<picker mode="selector" :range="routeNameAndId" range-key="routeName"
						@change="handlecurrentSelectRouteNameAndIdChange"
						style="display: flex;justify-content: center;align-items: center;">
						<view v-if="hasChooseRoute">
							{{UpdateInterfaceData.routeId+'号路线: ' +currentSelectRouteNameAndId.routeName}}
						</view>
						<view v-if="!hasChooseRoute">{{'请选择路线' }}</view>
					</picker>
				</view>
				<view
					style="display: flex;flex-direction: row;justify-content: start;align-items: center;width: calc(100% - 40px);margin-bottom: 10px;border-bottom:#cecece 2px solid;padding: 10px;">
					<input type="number" placeholder="小时" v-model="selectHour" @input="updateStartTime"
						style="text-align: center;width: 50%;" />
					<text style="margin-left: 4px;margin-right: 4px;">时</text>
					<input type="number" placeholder="分钟" v-model="selectMinute" @input="updateStartTime"
						style="text-align: center;width: 50%;" />
					<text style="margin-left: 4px;margin-right: 4px;">分</text>
				</view>
				<view
					style="display: flex;width: calc(100% - 40px);margin-bottom: 10px;border-bottom:#cecece 2px solid;padding: 10px;">
					<picker mode="selector" :range="scheduleTypes" @change="handlecurrentSelectScheduleType"
						style="display: flex;justify-content: center;align-items: center;width: 100%;"
						v-if="UpdateInterfaceData.scheduleType==='daily' || UpdateInterfaceData.scheduleType==='once'">
						<text v-if="UpdateInterfaceData.scheduleType === 'daily'">每天</text>
						<text v-if="UpdateInterfaceData.scheduleType==='once'">只执行一次</text>
						<text v-if="UpdateInterfaceData.scheduleType==='weekly'">每周</text>
						<text v-if="UpdateInterfaceData.scheduleType==='monthly'">每月</text>
					</picker>
					<view
						style="display: flex;flex-direction: row;justify-content: start;align-items: center;width: 100%;"
						v-if="UpdateInterfaceData.scheduleType==='weekly' || UpdateInterfaceData.scheduleType==='monthly'">
						<picker mode="selector" :range="scheduleTypes" @change="handlecurrentSelectScheduleType"
							style="display: flex;justify-content: center;align-items: center;width: 50%;">
							<text v-if="UpdateInterfaceData.scheduleType === 'daily'">每天</text>
							<text v-if="UpdateInterfaceData.scheduleType==='once'">只执行一次</text>
							<text v-if="UpdateInterfaceData.scheduleType==='weekly'">每周</text>
							<text v-if="UpdateInterfaceData.scheduleType==='monthly'">每月</text>
						</picker>
						<view style="width: 50%;display: flex;align-items: center;justify-content: center;">
							<text style="margin-left: 4px;margin-right: 4px;">第</text>
							<input type="number" placeholder="请填写第几天" v-model="selectWhichDay" @input="updateWhichDay"
								style="text-align: center;padding: 10px" />
							<text style="margin-left: 4px;margin-right: 4px;">天</text>
						</view>
					</view>
				</view>
			</view>



			<view
				style="height: 80px;width: 100%;display: flex;flex-direction: row;align-items: center;justify-content: space-around;font-size: 16px;">
				<view
					style="width: 140px;padding:10px ;;background-color: #f5f5f5;border-radius: 14px;align-items: center;justify-content: center;display: flex;"
					@click="clickToUpdateInterfaceHide()">
					<image src="/static/icons/cancel.png" style="height: 24px;width: 24px;" mode="aspectFit"></image>
					<text style="margin-left: 4px;">取消</text>
				</view>
				<view @click="clickUpdateAction()" v-if="UpdateInterfaceData.interfaceVisual==='update'"
					style="width: 140px;padding:10px ;background-color: #f5f5f5;border-radius: 14px;align-items: center;justify-content: center;display: flex;">
					<image src="/static/icons/sync.png" style="height: 24px;width: 24px;" mode="aspectFit"></image>
					<text style="margin-left: 4px;">保存</text>
				</view>
				<view @click="clickUpdateAction()" v-if="UpdateInterfaceData.interfaceVisual==='add'"
					style="width: 140px;padding:10px ;background-color: #f5f5f5;border-radius: 14px;align-items: center;justify-content: center;display: flex;">
					<image src="/static/icons/add.png" style="height: 24px;width: 24px;" mode="aspectFit"></image>
					<text style="margin-left: 4px;">添加</text>
				</view>
			</view>
		</view>

		<view
			style="display: flex;position: fixed;z-index: 1;bottom: 150px;left: 10px;background-color: rgba(255, 255, 255, 0.9);border-radius: 25px;height: 120px;width: 50px;align-items: center;justify-content: center;border: #c3c3c3 1px solid;flex-direction: column;">
			<view
				style="height: 50px;width: 50px;display: flex;align-items: center;justify-content: center;margin-bottom: 20px;"
				@click="clickToAddAction()">
				<image src="/static/icons/add.png" mode="aspectFit" style="height: 25px;width: 25px;"></image>
			</view>
			<view style="height: 50px;width: 50px;display: flex;align-items: center;justify-content: center;"
				@click="switchDelete()">
				<image src="/static/icons/delete_red.png" mode="aspectFit" style="height: 25px;width: 25px;"></image>
			</view>
		</view>


		<view style="width: 100%;padding: 20px;height: 100%;overflow-y: scroll;">
			<view v-for="droneAction in allDroneActions" :key="droneAction.droneActionId"
				style="width: calc(100% - 40px);;height: 100px;border-radius: 20px;background-color: #ffffff;margin-bottom: 20px;display: flex;flex-direction: row;align-items: center;color: #757575;">
				<image src="/static/icons/delete_red.png" mode="aspectFit"
					style="height: 40px;width: 40px;margin-left: 10px;" v-if="isDelete"
					@click="deleteAction(droneAction.droneActionId)"></image>
				<view style="width: 100%;margin-left: 20px;display: flex;flex-direction: column;">
					<view style="display: flex;flex-direction: row;align-items: center;"
						@click="clickToUpdateInterfaceVisual(droneAction.droneActionId,droneAction.droneId,droneAction.routeId,droneAction.startTime,droneAction.scheduleType,droneAction.whichDay,droneAction.enabled)">
						<text style="font-size: 28px;margin-right: 4px;">
							{{ formatTime(droneAction.startTime) }}
						</text>
						<text style="font-size: 20px;margin-top: 4px;">
							{{ droneAction.routeName }}
						</text>
					</view>
					<view style="display: flex;flex-direction: row;align-items: center;">
						<text style="font-size: 14px;margin-right: 4px;">
							{{ droneAction.droneId }}号无人机
						</text>
						<text style="font-size: 14px;">
							{{ formatDate(droneAction.scheduleType,droneAction.whichDay) }}
						</text>
					</view>
				</view>
				<image :src="droneAction.enabled ? '/static/icons/switch_on.png' : '/static/icons/switch_off.png'"
					mode="aspectFit" style="height: 80px;width: 80px;margin-right: 20px;"
					@click="switchActionStatus(droneAction.droneActionId,droneAction.enabled)" />
			</view>
			<view style="height: 20px;"></view>
		</view>

	</PageLayout>
</template>

<script setup>
	import PageLayout from "/pages/PageLayout/PageLayout.vue";
	import {
		navigateToControl,
		navigateTodroneAction,
		fetchActiveRouteNameAndIdList,
		fetchDroneIdList
	} from "/utils/Utils";
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted
	} from "vue";
	// 创建行为
	const createAction = async (action) => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + '/actions/createAction',
				method: 'POST',
				data: action,
				header: {
					'Content-Type': 'application/json'
				}
			});
			if (response.statusCode === 200) {
				uni.showToast({
					title: '行为创建成功',
					icon: 'success'
				});
				return response.data;
			} else {
				console.error('创建失败，状态码:', response.statusCode);
				uni.showToast({
					title: '行为创建失败',
					icon: 'error'
				});
			}
		} catch (error) {
			console.error('请求异常:', error);
			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};
	//点击切换行为开和关
	const switchActionStatus = (actionId, enabled) => {
		toggleActionStatus(actionId, !enabled);
	};
	const isDelete = ref(false);
	//点击切换是否删除
	const switchDelete = () => {
		isDelete.value = !isDelete.value;
	}
	// 发送切换行为请求
	const toggleActionStatus = async (actionId, enabled) => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl +
					`/actions/toggleActionStatus?actionId=${actionId}&enabled=${enabled}`,
				method: 'PUT'
			});
			if (response.statusCode === 200) {
				// uni.showToast({
				//     title: '状态更新成功',
				//     icon: 'success'
				// });
				// console.log(response.data);
			} else {
				console.error('状态更新失败，状态码:', response.statusCode);
				uni.showToast({
					title: '状态更新失败',
					icon: 'error'
				});
			}
		} catch (error) {
			console.error('请求异常:', error);
			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	const UpdateInterfaceData = ref({
		"interfaceVisual": "hide"
	});
	const clickToUpdateInterfaceVisual = (droneActionId, droneId, routeId, startTime, scheduleType, whichDay, enabled) => {
		UpdateInterfaceData.value = {};
		UpdateInterfaceData.value = {
			"droneActionId": droneActionId,
			"droneId": droneId,
			"routeId": routeId,
			"startTime": startTime,
			"scheduleType": scheduleType,
			"whichDay": whichDay,
			"enabled": enabled,
			"interfaceVisual": "update",
		}
		const date = new Date(startTime);
		selectHour.value = date.getUTCHours().toString().padStart(2, '0');
		selectMinute.value = date.getUTCMinutes().toString().padStart(2, '0');
		getDroneIdList();
		getRouteNameAndId();
	};
	const clickToAddAction = () => {
		UpdateInterfaceData.value = {};
		UpdateInterfaceData.value = {
			"droneActionId": null,
			"droneId": null,
			"routeId": null,
			"startTime": null,
			"scheduleType": "once",
			"whichDay": null,
			"enabled": false,
			"interfaceVisual": "add",
		}
		getDroneIdList();
		getRouteNameAndId();
	};
	const clickToUpdateInterfaceHide = () => {
		hasChooseDrone.value = false;
		hasChooseRoute.value = false;
		routeNameAndId.value = [];
		droneIdList.value = [];
		currentSelectRouteNameAndId.value = {};
		currentSelectDroneId.value = null;
		selectHour.value = "";
		selectMinute.value = "";
		UpdateInterfaceData.value = {
			"interfaceVisual": "hide"
		};
	};
	const switchUpdateInterfaceDataEnabled = () => {
		UpdateInterfaceData.value.enabled = !UpdateInterfaceData.value.enabled;

	};
	const clickUpdateAction = () => {
		if (UpdateInterfaceData.value.interfaceVisual === "add") {
			if (UpdateInterfaceData.value.droneId === null || UpdateInterfaceData.value.routeId === null ||
				UpdateInterfaceData.value.startTime === null ||
				((UpdateInterfaceData.value.scheduleType === "weekly" || UpdateInterfaceData.value.scheduleType ===
					"monthly") && UpdateInterfaceData.value.whichDay === null)) {
				uni.showToast({
					title: '缺少必要参数',
					icon: 'error'
				});
				return;
			}
			const action = {
				"droneActionId": UpdateInterfaceData.value.droneActionId,
				"droneId": UpdateInterfaceData.value.droneId,
				"routeId": UpdateInterfaceData.value.routeId,
				"startTime": UpdateInterfaceData.value.startTime,
				"scheduleType": UpdateInterfaceData.value.scheduleType,
				"whichDay": UpdateInterfaceData.value.whichDay,
				"enabled": UpdateInterfaceData.value.enabled,
			}
			createAction(action);
		}
		if (UpdateInterfaceData.value.interfaceVisual === "update") {
			if ((UpdateInterfaceData.value.scheduleType === "weekly" || UpdateInterfaceData.value.scheduleType ===
					"monthly") && UpdateInterfaceData.value.whichDay === null) {
				uni.showToast({
					title: '缺少必要参数',
					icon: 'error'
				});
				return;
			}
			const action = {
				"droneActionId": UpdateInterfaceData.value.droneActionId,
				"droneId": UpdateInterfaceData.value.droneId,
				"routeId": UpdateInterfaceData.value.routeId,
				"startTime": UpdateInterfaceData.value.startTime,
				"scheduleType": UpdateInterfaceData.value.scheduleType,
				"whichDay": UpdateInterfaceData.value.whichDay,
				"enabled": UpdateInterfaceData.value.enabled,
			}
			updateAction(action);
		}
		clickToUpdateInterfaceHide();
	};
	//存储是否选择无人机
	const hasChooseDrone = ref(false);
	//存储是否选择路线
	const hasChooseRoute = ref(false);
	// 存储路线id和名称
	const routeNameAndId = ref([]);
	// 存储无人机ID列表
	const droneIdList = ref([]);
	//存储所选路线名称和id
	const currentSelectRouteNameAndId = ref({});
	//存储所选无人机id
	const currentSelectDroneId = ref();
	//存储所填的小时
	const selectHour = ref("");
	//存储所填的分钟
	const selectMinute = ref("");
	//存储所选执行日期
	const selectWhichDay = ref("");

	//存储可选的scheduleType
	const scheduleTypes = ref(["只执行一次", "每天", "每周", "每月"]);


	const updateWhichDay = () => {
		if (selectWhichDay.value != "") {
			if (UpdateInterfaceData.value.scheduleType === "weekly") {
				let remainder = Number(selectWhichDay.value) % 7;
				if (remainder == 0) {
					UpdateInterfaceData.value.whichDay = 7;
					return;
				}
				UpdateInterfaceData.value.whichDay = remainder;
				return;
			}
			if (UpdateInterfaceData.value.scheduleType === "monthly") {
				let remainder = Number(selectWhichDay.value) % 31;
				if (remainder == 0) {
					UpdateInterfaceData.value.whichDay = 31;
					return;
				}
				UpdateInterfaceData.value.whichDay = remainder;
				return;
			}
		}
	}
	const handlecurrentSelectScheduleType = (e) => {
		const selectedIndex = e.detail.value;
		if (selectedIndex === 0) {
			UpdateInterfaceData.value.scheduleType = "once";
		}
		if (selectedIndex === 1) {
			UpdateInterfaceData.value.scheduleType = "daily";
		}
		if (selectedIndex === 2) {
			UpdateInterfaceData.value.scheduleType = "weekly";
			let remainder = UpdateInterfaceData.value.whichDay % 7;
			if (remainder == 0) {
				UpdateInterfaceData.value.whichDay = 7;
			} else {
				UpdateInterfaceData.value.whichDay = remainder;
			}
		}
		if (selectedIndex === 3) {
			UpdateInterfaceData.value.scheduleType = "monthly";
			let remainder = UpdateInterfaceData.value.whichDay % 31;
			if (remainder == 0) {
				UpdateInterfaceData.value.whichDay = 31;
			} else {
				UpdateInterfaceData.value.whichDay = remainder;
			}
		}
	};

	// 更新 UpdateInterface时间
	const updateStartTime = () => {
		if (selectHour.value === "" || selectMinute.value === "") return; // 如果未输入数据，返回
		const now = new Date();
		now.setHours(Number(selectHour.value));
		now.setMinutes(Number(selectMinute.value));
		now.setSeconds(0);
		now.setMilliseconds(0);
		UpdateInterfaceData.value.startTime = now.toISOString().replace('Z', '+16:00');
	};
	const getDroneIdList = async () => {
		droneIdList.value = await fetchDroneIdList();
	};

	const getRouteNameAndId = async () => {
		routeNameAndId.value = await fetchActiveRouteNameAndIdList();
	};

	const handlecurrentSelectRouteNameAndIdChange = (e) => {
		const selectedIndex = e.detail.value;
		UpdateInterfaceData.value.routeId = routeNameAndId.value[selectedIndex].id;
		currentSelectRouteNameAndId.value = routeNameAndId.value[selectedIndex];
		hasChooseRoute.value = true;
	};

	const handlecurrentSelectDroneIdChange = (e) => {
		const selectedIndex = e.detail.value;
		UpdateInterfaceData.value.droneId = droneIdList.value[selectedIndex];
		hasChooseDrone.value = true;
	};

	// 更新行为
	const updateAction = async (action) => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + '/actions/updateAction',
				method: 'POST',
				data: action,
				header: {
					'Content-Type': 'application/json'
				}
			});
			if (response.statusCode === 200) {
				uni.showToast({
					title: '行为更新成功',
					icon: 'success'
				});
				return response.data;
			} else {
				console.error('更新失败，状态码:', response.statusCode);
				uni.showToast({
					title: '行为更新失败',
					icon: 'error'
				});
			}
		} catch (error) {
			console.error('请求异常:', error);
			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};

	// 删除行为
	const deleteAction = async (actionId) => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + `/actions/deleteAction?actionId=${actionId}`,
				method: 'DELETE'
			});
			if (response.statusCode === 200) {
				uni.showToast({
					title: '行为删除成功',
					icon: 'success'
				});
				return response.data;
			} else {
				console.error('删除失败，状态码:', response.statusCode);
				uni.showToast({
					title: '行为删除失败',
					icon: 'error'
				});
			}
		} catch (error) {
			console.error('请求异常:', error);
			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
		}
	};


	const allDroneActions = ref([]);
	// 获取所有行为及路径
	const getAllDroneAction = async () => {
		try {
			const response = await uni.request({
				url: getApp().globalData.rootUrl + '/actions/getAllDroneAction',
				method: 'GET'
			});
			if (response.statusCode === 200) {
				allDroneActions.value = [];
				allDroneActions.value = response.data.data;
			} else {
				console.error('获取失败，状态码:', response.statusCode);
				uni.showToast({
					title: '获取行为数据失败',
					icon: 'error'
				});
				return [];
			}
		} catch (error) {
			console.error('请求异常:', error);
			uni.showToast({
				title: `请求异常：${error.errMsg || error.message}`,
				icon: 'none',
				duration: 3000
			});
			return [];
		}
	};

	const formatTime = (timeString) => {
		const date = new Date(timeString);
		const hours = date.getUTCHours().toString().padStart(2, '0');
		const minutes = date.getUTCMinutes().toString().padStart(2, '0');
		return `${hours}:${minutes}`;
	};


	const formatDate = (scheduleType, whichDay) => {
		if (scheduleType == "daily") {
			return `每天`;
		}
		if (scheduleType == "once") {
			return `只执行一次`;
		}
		if (scheduleType == "weekly") {
			return `每周第${whichDay}天`;
		}
		if (scheduleType == "monthly") {
			return `每月第${whichDay}天`;
		}
	}
	const timer = ref(null);
	onMounted(() => {
		timer.value = setInterval(() => {
			getAllDroneAction();
		}, 1000);
	});

	onUnmounted(() => {
		if (timer.value) clearInterval(timer.value);
	});
</script>

<style lang="scss" scoped>

</style>